//
//  ByFileManager.m
//  laserdevice_ios
//
//  Created by pro on 16/12/13.
//  Copyright © 2016年 com.itboye. All rights reserved.
//

#import "ByFileManager.h"

@implementation ByFileManager

#define KFileManager [NSFileManager defaultManager]

#pragma mark - 通用
// 沙盒路径
+ (void)homePath {
    
    NSLog(@"根目录:%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]);
}


// 根据名称获得路径
+ (NSString *)pathWithDocOrFileName:(NSString *)name {
    
    
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:name];
}


// 创建文件夹，用于存储场景数据
+ (BOOL)createDocument:(NSString *)ducName
               existed:(void (^)(void))existedBlock
               failure:(void (^)(NSError *error))failureBlock {
    
    NSString *path = [self pathWithDocOrFileName:ducName];
    // 文件夹不存在，则创建文件夹，否则调用已存在回调
    if ([KFileManager fileExistsAtPath:path] == NO) {
        
        NSError *error = nil;
        [KFileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            if (failureBlock) {
                failureBlock(error);
            }
            return NO;
        }

    } else {
        if (existedBlock) {
            existedBlock();
        }
        return NO;
    }
    return YES;
}

// 创建文件
+ (BOOL)createFile:(NSString *)fileName
              data:(NSData *)data
           existed:(void (^)(void))existedBlock {
    
    NSString *path = [self pathWithDocOrFileName:fileName];
    // 文件夹不存在，则创建文件夹，否则调用已存在回调
    if ([KFileManager fileExistsAtPath:path] == NO) {
        
        [KFileManager createFileAtPath:path contents:data attributes:nil];
        
    } else {
        if (existedBlock) {
            existedBlock();
        }
        return NO;
    }
    return YES;
}

// 移除文件或文件夹
+ (BOOL)removeDocumentOrFileWithPathName:(NSString *)pathName
                                 failure:(void (^)(NSError *error))failureBlock {
    
    NSError *error = nil;
    [KFileManager removeItemAtPath:[self pathWithDocOrFileName:pathName] error:&error];
    if (error) {
        if (failureBlock) {
            failureBlock(error);
        }
        return NO;
    }
    return YES;
}

// 获取所有某路径下所有文件夹的路径
+ (NSArray *)getAllDirPathAtPath:(NSString *)path {
    
    BOOL isExist = [KFileManager fileExistsAtPath:path isDirectory:NULL];
    if (isExist) {
        NSArray *files = [KFileManager contentsOfDirectoryAtPath:path error:nil];
        NSMutableArray *allDir = [[NSMutableArray alloc] init];
        for (NSString *subStr in files) {
            BOOL isDir;
            NSString *subPath = [path stringByAppendingPathComponent:subStr];
            if ([KFileManager fileExistsAtPath:subPath isDirectory:&isDir] && isDir) {

                [allDir addObject:subPath];
            } else {

            }
        }
        
        return allDir;
    }
    
    return nil;
}
+ (NSArray *)getAllDataHasSuffix:(NSString *)suffix atPath:(NSString *)path {
    
    BOOL isExist = [KFileManager fileExistsAtPath:path isDirectory:NULL];
    if (isExist) {
        NSArray *files = [KFileManager contentsOfDirectoryAtPath:path error:nil];
        NSMutableArray *allDatas = [[NSMutableArray alloc] init];
        for (NSString *subStr in files) {
            BOOL isDir;
            NSString *subPath = [path stringByAppendingPathComponent:subStr];
            if ([KFileManager fileExistsAtPath:subPath isDirectory:&isDir] && isDir) {
                
            } else {
                if ([subStr hasSuffix:suffix]) {
                    NSData *data = [NSData dataWithContentsOfFile:subPath];
                    [allDatas addObject:data];
                }
            }
        }
        return allDatas;
    }
    
    return nil;
}


#pragma mark - 场景相关
+ (void)saveSceneWithName:(NSString *)sceneName
                  bgImage:(UIImage *)bgImage
              shapeImages:(NSArray *)shapeImages
                     json:(NSData *)jsonData
                  existed:(void (^)(void))existedBlock
                  failure:(void (^)(NSError *error))failureBlock {
    
    NSString *scenesDocument = @"MyScenes";
    // 0.创建沙盒路径下documents路径下的场景总文件夹（包含所有场景文件夹）
    [self createDocument:scenesDocument existed:nil failure:failureBlock];
   
    
    NSString *scenePath = [scenesDocument stringByAppendingPathComponent:sceneName];
    
    // 1.创建沙盒路径下documents路径下的场景文件夹（一个场景对应一个文件夹）
    [self createDocument:scenePath existed:^ {
        
         [UIAlertView showWithTitle:STRING(@"baocunchangjing") message:STRING(@"baocunceliangshuju-jinggao") cancelButtonTitle:STRING(@"fou") otherButtonTitles:@[STRING(@"fugai")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
            if (buttonIndex == 1) {
                [self removeDocumentOrFileWithPathName:scenePath failure:nil];
                [self createDocument:scenePath existed:nil failure:nil];
                // 2.创建该文件夹路径下的图片文件夹
                BOOL success = [self createDocument:[NSString stringWithFormat:@"%@/images", scenePath] existed:existedBlock failure:failureBlock];
                if (!success) {
                    return;
                }
                
                // 2-1.把背景图片保存到图片文件夹下
                if (bgImage) {
                    [self createFile:[NSString stringWithFormat:@"%@/images/bg.png", scenePath] data:UIImagePNGRepresentation(bgImage) existed:nil];
                }
                
                // 2-2.遍历模型图片数组，将图片存在图片文件夹下
                for (UIImage *image in shapeImages) {
                    NSInteger index = [shapeImages indexOfObject:image];
                    NSData *data = UIImagePNGRepresentation(image);
                    NSString *imageName = [NSString stringWithFormat:@"image%li.png", index + 1];
                    
                    [self createFile:[NSString stringWithFormat:@"%@/images/%@", scenePath, imageName] data:data existed:nil];
                }
                
                // 3.保存json文件
                [self createFile:[NSString stringWithFormat:@"%@/%@.json", scenePath, sceneName] data:jsonData existed:nil];
                return;
            } else {
                return;
            }
        }];
    } failure:nil];
   
    
    // 2.创建该文件夹路径下的图片文件夹
    BOOL success = [self createDocument:[NSString stringWithFormat:@"%@/images", scenePath] existed:existedBlock failure:failureBlock];
    if (!success) {
        return;
    }
    
    // 2-1.把背景图片保存到图片文件夹下
    if (bgImage) {
        [self createFile:[NSString stringWithFormat:@"%@/images/bg.png", scenePath] data:UIImagePNGRepresentation(bgImage) existed:nil];
    }

    // 2-2.遍历模型图片数组，将图片存在图片文件夹下
    for (UIImage *image in shapeImages) {
        NSInteger index = [shapeImages indexOfObject:image];
        NSData *data = UIImagePNGRepresentation(image);
        NSString *imageName = [NSString stringWithFormat:@"image%li.png", index + 1];
        
        [self createFile:[NSString stringWithFormat:@"%@/images/%@", scenePath, imageName] data:data existed:nil];
    }
    
    // 3.保存json文件
    [self createFile:[NSString stringWithFormat:@"%@/%@.json", scenePath, sceneName] data:jsonData existed:nil];

}


// 保存为PDF
+ (void)saveSceneForPDFWithName:(NSString *)sceneName
                          image:(UIImage *)image
                           size:(CGSize)size
                           json:(NSData *)jsonData {
    
    NSString *scenesDocument = @"MyScenes";
    // 0.创建沙盒路径下documents路径下的场景总文件夹（包含所有场景文件夹）
    [self createDocument:scenesDocument existed:nil failure:nil];
    
    NSString *scenePath = [scenesDocument stringByAppendingPathComponent:sceneName];
    
    // 1.创建沙盒路径下documents路径下的场景文件夹（一个场景对应一个文件夹）
    [self createDocument:scenePath existed:^ {
        
        [UIAlertView showWithTitle:STRING(@"baocunchangjing") message:STRING(@"baocunceliangshuju-jinggao") cancelButtonTitle:STRING(@"fou") otherButtonTitles:@[STRING(@"fugai")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
            if (buttonIndex == 1) {
                [self removeDocumentOrFileWithPathName:scenePath failure:nil];
                [self createDocument:scenePath existed:nil failure:nil];
                
                // 保存图片
                NSData *data = UIImagePNGRepresentation(image);
                NSString *imageName = [NSString stringWithFormat:@"%@.png", sceneName];
                [self createFile:[NSString stringWithFormat:@"%@/%@", scenePath, imageName] data:data existed:nil];
    
                // 保存json
                [self createFile:[NSString stringWithFormat:@"%@/%@.json", scenePath, sceneName] data:jsonData existed:nil];
                
                // 保存pdf
                NSString *pdfPath = [self pathWithDocOrFileName:[NSString stringWithFormat:@"%@/%@.pdf", scenePath, sceneName]];
                UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
                UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);
                [image drawAtPoint:CGPointMake(0, 0)];
                UIGraphicsEndPDFContext();
                
                return;
            } else {
                return;
            }
        }];
    } failure:nil];
    
    // 保存图片
    NSData *data = UIImagePNGRepresentation(image);
    NSString *imageName = [NSString stringWithFormat:@"%@.png", sceneName];
    [self createFile:[NSString stringWithFormat:@"%@/%@", scenePath, imageName] data:data existed:nil];
    
    // 保存json
    [self createFile:[NSString stringWithFormat:@"%@/%@.json", scenePath, sceneName] data:jsonData existed:nil];
    
    // 保存pdf
    NSString *pdfPath = [self pathWithDocOrFileName:[NSString stringWithFormat:@"%@/%@.pdf", scenePath, sceneName]];
    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);
    [image drawAtPoint:CGPointMake(0, 0)];
    UIGraphicsEndPDFContext();
    
}

+ (void)deleteSceneWithName:(NSString *)sceneName
                    success:(void (^)(void))successBlock
                    failure:(void (^)(NSError *error))failureBlock {

    NSString *scenePath = [NSString stringWithFormat:@"MyScenes/%@", sceneName];
    
    if ([self removeDocumentOrFileWithPathName:scenePath failure:failureBlock]) {
        
        if (successBlock) {
            successBlock();
        }
    }
}

// 获得所有场景（字典）
+ (NSArray *)allScenes {
    
    NSString *path = [self pathWithDocOrFileName:@"MyScenes"];
    
    NSArray *allDirPath = [self getAllDirPathAtPath:path];

    NSMutableArray *retArray = [[NSMutableArray alloc] init];
    for (NSString *path in allDirPath) {
        if ([self getJsonDicAtScenePath:path] != nil) {
            [retArray addObject:[self getJsonDicAtScenePath:path]];
        }
    }
    
    return retArray.copy;
}

// 获得某场景的json字典
+ (NSDictionary *)getJsonDicAtScenePath:(NSString *)path {
    
    NSData *jsonData = [[self getAllDataHasSuffix:@"json" atPath:path] lastObject];

    if (jsonData == nil) {
        return nil;
    }
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
  
    return dic;
}

// 获得图片
+ (UIImage *)getImageAtScene:(NSString *)sceneName imagePath:(NSString *)imagePath {
    
    NSString *path = [self pathWithDocOrFileName:@"MyScenes"];
    path = [path stringByAppendingPathComponent:sceneName];
    path = [path stringByAppendingPathComponent:[imagePath componentsSeparatedByString:@"/"][1]];
    NSArray *imageDatas = [self getAllDataHasSuffix:[imagePath componentsSeparatedByString:@"/"].lastObject atPath:path];
    NSData *imageData = [imageDatas lastObject];
    UIImage *image = [UIImage imageWithData:imageData];

    return image;
}




#pragma mark - 数据导入
+ (void)saveHistoryWithName:(NSString *)name
                       json:(NSData *)jsonData
                    existed:(void (^)(void))existedBlock
                    failure:(void (^)(NSError *error))failureBlock {
    
    NSString *historyDocument = @"MyHistorys";
    // 0.创建沙盒路径下documents路径下的数据导入历史总文件夹
    [self createDocument:historyDocument existed:nil failure:failureBlock];
    
    
    NSString *historyPath = [historyDocument stringByAppendingPathComponent:name];
    
    [self createDocument:historyPath existed:^ {
        
        [UIAlertView showWithTitle:STRING(@"baocun excel") message:STRING(@"baocun excel-jinggao") cancelButtonTitle:STRING(@"fou") otherButtonTitles:@[STRING(@"fugai")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
            if (buttonIndex == 1) {
                [self removeDocumentOrFileWithPathName:historyPath failure:nil];
                [self createDocument:historyPath existed:nil failure:nil];
            
                // 保存json文件
                [self createFile:[NSString stringWithFormat:@"%@/%@.json", historyPath, name] data:jsonData existed:nil];
                return;
            } else {
                return;
            }
        }];
    } failure:nil];
    
    
    // 保存json文件
    [self createFile:[NSString stringWithFormat:@"%@/%@.json", historyPath, name] data:jsonData existed:nil];
    
}

+ (void)deleteHistoryWithName:(NSString *)name
                      success:(void (^)(void))successBlock
                      failure:(void (^)(NSError *error))failureBlock {
    
    NSString *scenePath = [NSString stringWithFormat:@"MyHistorys/%@", name];
    
    if ([self removeDocumentOrFileWithPathName:scenePath failure:failureBlock]) {
        
        if (successBlock) {
            successBlock();
        }
    }
}



+ (NSArray *)allHistorys {
    
    NSString *path = [self pathWithDocOrFileName:@"MyHistorys"];
    
    NSArray *allDirPath = [self getAllDirPathAtPath:path];
    
    NSMutableArray *retArray = [[NSMutableArray alloc] init];
    for (NSString *path in allDirPath) {
        if ([self getJsonDicAtScenePath:path] != nil) {
            [retArray addObject:[self getJsonDicAtScenePath:path]];
        }
    }
    
    return retArray.copy;
}


#pragma mark - 实时测量
// 保存为PDF
+ (void)saveMeastureForPDFWithName:(NSString *)name
                             image:(UIImage *)image
                              size:(CGSize)size
                              json:(NSData *)jsonData {
    
    NSString *document = @"MyMeatures";
    // 0.创建沙盒路径下documents路径下的场景总文件夹（包含所有场景文件夹）
    [self createDocument:document existed:nil failure:nil];
    
    NSString *path = [document stringByAppendingPathComponent:name];
    
    // 1.创建沙盒路径下documents路径下的场景文件夹（一个场景对应一个文件夹）
    [self createDocument:path existed:^ {
        
        [UIAlertView showWithTitle:STRING(@"baocunceliangshuju") message:STRING(@"baocunceliangshuju-jinggao") cancelButtonTitle:STRING(@"fou") otherButtonTitles:@[STRING(@"fugai")] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
            if (buttonIndex == 1) {
                [self removeDocumentOrFileWithPathName:path failure:nil];
                [self createDocument:path existed:nil failure:nil];
                
                // 保存图片
                NSData *data = UIImagePNGRepresentation(image);
                NSString *imageName = [NSString stringWithFormat:@"%@.png", name];
                [self createFile:[NSString stringWithFormat:@"%@/%@", path, imageName] data:data existed:nil];
                
                // 保存json
                [self createFile:[NSString stringWithFormat:@"%@/%@.json", path, name] data:jsonData existed:nil];
                
                // 保存pdf
                NSString *pdfPath = [self pathWithDocOrFileName:[NSString stringWithFormat:@"%@/%@.pdf", path, name]];
                UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
                UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);
                [image drawAtPoint:CGPointMake(0, 0)];
                UIGraphicsEndPDFContext();
                
                return;
            } else {
                return;
            }
        }];
    } failure:nil];
    
    // 保存图片
    NSData *data = UIImagePNGRepresentation(image);
    NSString *imageName = [NSString stringWithFormat:@"%@.png", name];
    [self createFile:[NSString stringWithFormat:@"%@/%@", path, imageName] data:data existed:nil];
    
    // 保存json
    [self createFile:[NSString stringWithFormat:@"%@/%@.json", path, name] data:jsonData existed:nil];
    
    // 保存pdf
    NSString *pdfPath = [self pathWithDocOrFileName:[NSString stringWithFormat:@"%@/%@.pdf", path, name]];
    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, size.width, size.height), nil);
    [image drawAtPoint:CGPointMake(0, 0)];
    UIGraphicsEndPDFContext();
}

+ (void)deleteMeastureWithName:(NSString *)name
                       success:(void (^)(void))successBlock
                       failure:(void (^)(NSError *error))failureBlock {
    
    NSString *scenePath = [NSString stringWithFormat:@"MyMeatures/%@", name];
    
    if ([self removeDocumentOrFileWithPathName:scenePath failure:failureBlock]) {
        
        if (successBlock) {
            successBlock();
        }
    }
}


+ (NSArray *)allMeastures {
    
    NSString *path = [self pathWithDocOrFileName:@"MyMeatures"];
    
    NSArray *allDirPath = [self getAllDirPathAtPath:path];
    
    NSMutableArray *retArray = [[NSMutableArray alloc] init];
    for (NSString *path in allDirPath) {
        if ([self getJsonDicAtScenePath:path] != nil) {
            [retArray addObject:[self getJsonDicAtScenePath:path]];
        }
    }
    
    return retArray.copy;
}

+ (UIImage *)getImageAtMeasture:(NSString *)name imagePath:(NSString *)imagePath {
    
    NSString *path = [self pathWithDocOrFileName:@"MyMeatures"];
    path = [path stringByAppendingPathComponent:name];
    path = [path stringByAppendingPathComponent:[imagePath componentsSeparatedByString:@"/"][1]];
    NSArray *imageDatas = [self getAllDataHasSuffix:[imagePath componentsSeparatedByString:@"/"].lastObject atPath:path];
    NSData *imageData = [imageDatas lastObject];
    UIImage *image = [UIImage imageWithData:imageData];
    
    return image;
}

@end
